package com.cabrida.livestar.livestar;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.main.FansWebActivity;
import com.cabrida.livestar.main.GiftShowManager;
import com.cabrida.livestar.main.GiftVo;
import com.cabrida.livestar.model.JSONParser;
import com.cabrida.livestar.model.LiveAdvData;
import com.cabrida.livestar.model.StarGiftData;
import com.cabrida.livestar.model.StarMsgData;
import com.cabrida.livestar.util.DialogShareView;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.MyUtils;
import com.cabrida.livestar.util.NetworkUtils;
import com.cabrida.livestar.util.StringUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMGroupAddOpt;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberRoleType;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUser;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.rtmp.ITXLivePushListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePushConfig;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.ui.TXCloudVideoView;
/**
 * 明星端-直播间
 */
public class StarLiveRoomActivity extends BaseActivity {
	public static final String TAG = StarLiveRoomActivity.class.getSimpleName();
	TXLivePusher mLivePusher;
	TXCloudVideoView mCaptureView;
	private ImageButton ib_back;
	private TextView tv_notice;
	private ImageView iv_header;
	private TextView tv_name;
	private TextView tv_number;
	private String channel;
	private String shareTitle;
	private String shareContent;
	private ArrayList<LiveAdvData> listAdv = new ArrayList<LiveAdvData>();
	private int number=0;
	private ListView listView;
	private StarHomeLiveRoomMsgLvAdapter adapter;
	private ArrayList<StarMsgData> _list = new ArrayList<StarMsgData>();
	private ArrayList<StarGiftData> _list_gift = new ArrayList<StarGiftData>();

	private LinearLayout ll_write;
	private LinearLayout ll_btn;
	private LinearLayout ll_list;
	private RelativeLayout ll_red_packet;
	private Button btn_write;
	private Button btn_red_packet;
	private Button btn_send_red_packet;
	private Button btn_gift;
	private Button btn_overturn;
	private Button btn_beauty;
	private boolean isBeautify=true;
	private Button btn_share;
	
	private LinearLayout ll_gift;
	private Button btn_send_msg_gift;
	private Button btn_jian;
	private Button btn_jia;
	private TextView tv_clear;
	private TextView tv_account_money;
	private EditText et_red_packet_money_all;
	private EditText et_red_packet_number;
	private RadioButton radio_average;
	private RadioButton radio_random;
	private ImageButton ib_close_red_pakcet;

	private TextView tv_gift_1;
	private TextView tv_gift_2;
	private TextView tv_gift_3;
	private TextView tv_gift_4;
	private TextView tv_gift_name;
	private TextView tv_gift_sponsor;
	private TextView tv_gift_num;
	private TextView tv_gift_num_choice;
	private int positon = 1;

	private EditText et_content;
	private Button btn_send_msg;
	
	private ImageView iv_adv1;
	private ImageView iv_adv2;
	private ImageView iv_adv3;
	private ImageView iv_adv4;
	
	private LinearLayout gift_con;
	private GiftShowManager giftManger;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_star_live_room);
		ib_back = (ImageButton) findViewById(R.id.ib_back);
		iv_header = (ImageView) findViewById(R.id.iv_header);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_number = (TextView) findViewById(R.id.tv_number);
		listView = (ListView) findViewById(R.id.listView);
		gift_con = (LinearLayout) findViewById(R.id.gift_con);
		ll_write = (LinearLayout) findViewById(R.id.ll_write);
		ll_btn = (LinearLayout) findViewById(R.id.ll_btn);
		ll_gift = (LinearLayout) findViewById(R.id.ll_gift);
		ll_list = (LinearLayout) findViewById(R.id.ll_list);
		ll_red_packet = (RelativeLayout) findViewById(R.id.ll_red_packet);
		btn_write = (Button) findViewById(R.id.btn_write);
		et_content = (EditText) findViewById(R.id.et_content);
		btn_send_msg = (Button) findViewById(R.id.btn_send_msg);
		btn_gift = (Button) findViewById(R.id.btn_gift);
		btn_red_packet = (Button) findViewById(R.id.btn_red_packet);
		btn_overturn = (Button) findViewById(R.id.btn_overturn);
		btn_beauty = (Button) findViewById(R.id.btn_beauty);
		btn_send_red_packet = (Button) findViewById(R.id.btn_send_red_packet);
		btn_send_msg_gift = (Button) findViewById(R.id.btn_send_msg_gift);
		btn_share = (Button) findViewById(R.id.btn_share);
		btn_jian = (Button) findViewById(R.id.btn_jian);
		btn_jia = (Button) findViewById(R.id.btn_jia);
		tv_gift_1 = (TextView) findViewById(R.id.tv_gift_1);
		tv_gift_2 = (TextView) findViewById(R.id.tv_gift_2);
		tv_gift_3 = (TextView) findViewById(R.id.tv_gift_3);
		tv_gift_4 = (TextView) findViewById(R.id.tv_gift_4);
		tv_gift_name = (TextView) findViewById(R.id.tv_gift_name);
		tv_gift_sponsor = (TextView) findViewById(R.id.tv_gift_sponsor);
		tv_gift_num = (TextView) findViewById(R.id.tv_gift_num);
		tv_gift_num_choice = (TextView) findViewById(R.id.tv_gift_num_choice);
		tv_clear = (TextView) findViewById(R.id.tv_clear);
		tv_account_money = (TextView) findViewById(R.id.tv_account_money);
		et_red_packet_money_all = (EditText) findViewById(R.id.et_red_packet_money_all);
		et_red_packet_number = (EditText) findViewById(R.id.et_red_packet_number);
		radio_average = (RadioButton) findViewById(R.id.radio_average);
		radio_random = (RadioButton) findViewById(R.id.radio_random);
		ib_close_red_pakcet = (ImageButton) findViewById(R.id.ib_close_red_pakcet);
		tv_notice = (TextView) findViewById(R.id.tv_notice);
		iv_adv1 = (ImageView) findViewById(R.id.iv_adv1);
		iv_adv2 = (ImageView) findViewById(R.id.iv_adv2);
		iv_adv3 = (ImageView) findViewById(R.id.iv_adv3);
		iv_adv4 = (ImageView) findViewById(R.id.iv_adv4);
		
		MyUtils.loadImg(Global.headPic, iv_header);
		tv_name.setText(Global.S_name);
		tv_number.setText(number+"在线");
		
		giftManger = new GiftShowManager(context, gift_con);
		giftManger.showGift();// 开始显示礼物
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		ib_back.setOnClickListener(this);
		btn_write.setOnClickListener(this);
		btn_send_msg.setOnClickListener(this);
		btn_gift.setOnClickListener(this);
		btn_send_msg_gift.setOnClickListener(this);
		btn_overturn.setOnClickListener(this);
		btn_beauty.setOnClickListener(this);
		btn_jian.setOnClickListener(this);
		btn_jia.setOnClickListener(this);
		tv_gift_1.setOnClickListener(this);
		tv_gift_2.setOnClickListener(this);
		tv_gift_3.setOnClickListener(this);
		tv_gift_4.setOnClickListener(this);
		tv_clear.setOnClickListener(this);
		btn_red_packet.setOnClickListener(this);
		btn_send_red_packet.setOnClickListener(this);
		radio_average.setOnClickListener(this);
		radio_random.setOnClickListener(this);
		ib_close_red_pakcet.setOnClickListener(this);
		btn_share.setOnClickListener(this);
		iv_adv1.setOnClickListener(this);
		iv_adv2.setOnClickListener(this);
		iv_adv3.setOnClickListener(this);
		iv_adv4.setOnClickListener(this);
		adapter = new StarHomeLiveRoomMsgLvAdapter(context);
		listView.setAdapter(adapter);

		ll_write.setVisibility(View.INVISIBLE);
		ll_btn.setVisibility(View.VISIBLE);

//		int[] sdkver = TXLivePusher.getSDKVersion();
//		if (sdkver != null && sdkver.length >= 3) {
//			Log.d("rtmpsdk", "rtmp sdk version is:" + sdkver[0] + "."
//					+ sdkver[1] + "." + sdkver[2]);
//		}

		mLivePusher = new TXLivePusher(context);
		TXLivePushConfig mLivePushConfig = new TXLivePushConfig();
		mLivePusher.setConfig(mLivePushConfig);
		Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.share_live_leave);
		mLivePushConfig.setPauseImg(b);

		mCaptureView = (TXCloudVideoView) findViewById(R.id.video_view);
		mLivePusher.startCameraPreview(mCaptureView);
		mLivePusher.setBeautyFilter(5, 3);
		mLivePusher.setPushListener(new ITXLivePushListener() {

			@Override
			public void onPushEvent(int event, Bundle param) {
				// TODO Auto-generated method stub
				L.e(TAG, "mLivePusher---onPushEvent", "");
				if (event == TXLiveConstants.PUSH_EVT_CONNECT_SUCC) {
					StatusRoom();
				}
			}

			@Override
			public void onNetStatus(Bundle arg0) {
				// TODO Auto-generated method stub

			}
		});
		mCaptureView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ll_gift.setVisibility(View.INVISIBLE);
				ll_write.setVisibility(View.INVISIBLE);
				ll_btn.setVisibility(View.VISIBLE);
				ll_list.setVisibility(View.VISIBLE);
				ll_red_packet.setVisibility(View.INVISIBLE);
				hideSoftKeyboard();
			}
		});
		
		String rtmpUrl = getIntent().getStringExtra("rtmp");
		channel = getIntent().getStringExtra("channel");
		shareTitle = getIntent().getStringExtra("shareTitle");
		shareContent = getIntent().getStringExtra("shareContent");
		listAdv = (ArrayList<LiveAdvData>) getIntent().getSerializableExtra("list");
		mLivePusher.startPusher(rtmpUrl);
		
		OpenIm();
		
		
		if (null== listAdv||listAdv.size()==0||listAdv.size()!=4) {
			iv_adv1.setVisibility(View.GONE);
			iv_adv2.setVisibility(View.GONE);
			iv_adv3.setVisibility(View.GONE);
			iv_adv4.setVisibility(View.GONE);
		}else {
			MyUtils.loadImg(listAdv.get(0).getImg(), iv_adv1);
			MyUtils.loadImg(listAdv.get(1).getImg(), iv_adv2);
			MyUtils.loadImg(listAdv.get(2).getImg(), iv_adv3);
			MyUtils.loadImg(listAdv.get(3).getImg(), iv_adv4);
		}
	}

	private void getIMMsg(String response) {
		StarMsgData data = new StarMsgData();
		try {
			JSONObject obj = new JSONObject(response);
			if (!StringUtils.isBlank(obj.optString("userAction"))) {
				data.setUserAction(obj.optInt("userAction"));
			}
			if (!StringUtils.isBlank(obj.optString("nickName"))) {
				data.setNickName(obj.optString("nickName"));
			}
			if (!StringUtils.isBlank(obj.optString("userId"))) {
				data.setUserId(obj.optString("userId"));
			}
			if (!StringUtils.isBlank(obj.optString("headPic"))) {
				data.setHeadPic(obj.optString("headPic"));
			}
			String userAction = JsonUtils.getString(response, "userAction", "0");
			int ua = Integer.valueOf(userAction);
			if (Global.AVIMCMD_Fans_Present==ua) {
				if (!StringUtils.isBlank(obj.optString("msg"))) {
					if (obj.optString("msg").contains(",")) {
						String[] aaStrings = obj.optString("msg").split(",");
					data.setMsg(aaStrings[0]);
				}
				}
			}else{
				if (!StringUtils.isBlank(obj.optString("msg"))) {
					data.setMsg(obj.optString("msg"));
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		_list.add(data);
		adapter.setData(_list);
		adapter.notifyDataSetChanged();
		listView.setSelection(_list.size());
	}

	TIMUser user;

	private void OpenIm() {
		user = new TIMUser();
		user.setAccountType(Global.IMSDK_ACCOUNT_TYPE + "");
		user.setAppIdAt3rd(Global.IMSDK_APPID + "");
		user.setIdentifier(Global.U_id);
		
		// 初始化SDK基本配置
		TIMSdkConfig config = new TIMSdkConfig(Global.IMSDK_APPID);

		config.enableCrashReport(false);
		config.enableLogPrint(true);
		config.setLogLevel(TIMLogLevel.DEBUG);

		//初始化SDK
		TIMManager.getInstance().init(getApplicationContext(), config);
		
		// identifier为用户名，userSig 为用户登录凭证
		TIMManager.getInstance().login(Global.U_id, Global.TIm_Sig, new TIMCallBack() {
		    @Override
		    public void onError(int code, String desc) {
		        //错误码code和错误描述desc，可用于定位请求失败原因
		        //错误码code列表请参见错误码表
		        L.e(TAG, "statusroom_response", "login failed. code: " + code + " errmsg: " + desc);
		    }

		    @Override
		    public void onSuccess() {
		    	L.e(TAG, "statusroom_response", "TIMManager---onSuccess");
		    	TIMGroupManager.getInstance().applyJoinGroup(channel, "some reason", new TIMCallBack() {
		    	    @java.lang.Override
		    	    public void onError(int code, String desc) {
		    	        //接口返回了错误码code和错误描述desc，可用于原因
		    	        //错误码code列表请参见错误码表
		    	        Log.e(TAG, "disconnected");
		    	    }

		    	    @java.lang.Override
		    	    public void onSuccess() {
		    	        Log.i(TAG, "join group");
		    	        sendMsg(Global.AVIMCMD_Custom_EnterLive, "进入房间","");
		    	    }
		    	});
		    }
		});
		
		
		
		TIMManager.getInstance().addMessageListener(new TIMMessageListener() {

			@Override
			public boolean onNewMessages(List<TIMMessage> list) {
				// TODO Auto-generated method stub
				if (null==list||list.size()==0) {
					return false;
				}
				TIMMessage msg = list.get(0);
				TIMElem timelem = msg.getElement(0);
				if (timelem.getType() == TIMElemType.GroupSystem) {

				} else {
					TIMTextElem elem = (TIMTextElem) msg.getElement(0);
					String text = elem.getText();
					getIMMsg(text);
					String userAction = JsonUtils.getString(text, "userAction", "0");
					int ua = Integer.valueOf(userAction);
					if (Global.AVIMCMD_Custom_EnterLive==ua) {
						number++;
						tv_number.setText(number+"在线");
					}
					
					if (Global.AVIMCMD_Fans_Present==ua) {
						String message = JsonUtils.getString(text, "msg", "");
						if (message.contains(",")) {
							String[] aaStrings = message.split(",");
							String giftPos = aaStrings[1];
							GiftVo vo = new GiftVo();
							String nickName = JsonUtils.getString(text, "nickName", "");
							String headPic = JsonUtils.getString(text, "headPic", "");
							vo.setName(nickName);
							vo.setSendheader(headPic);
							vo.setNum(1);
							vo.setGiftName("花");
							vo.setImg(giftPos);
							giftManger.addGift(vo);
						}
					}
				}

				return false;
			}
		});
		
	}

	/** 修改房间状态 */
	private void StatusRoom() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("status", 1);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_STAR_CLOSE_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "statusroom_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String msg=JsonUtils.getString(data,"msg", "");
							tv_notice.setText(msg);
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}


	/** 关闭房间 */
	private void LeaveRoom() {
		// TODO Auto-generated method stub
		sendMsg(Global.AVIMCMD_Star_ExitLive, "主播退出房间","");
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("status", 3);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_STAR_CLOSE_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "closeroom_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							stopRtmpPublish();
							finish();
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/** 获取账户余额 */
	private void getAccountMoney() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_USER_BALANCE_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "closeroom_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String u_balance = JsonUtils.getString(data,
									"u_balance", "");
							ll_btn.setVisibility(View.INVISIBLE);
							ll_list.setVisibility(View.INVISIBLE);
							ll_red_packet.setVisibility(View.VISIBLE);
							tv_account_money.setText("账户余额："+u_balance);
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	
	/** 随机红包 
	 * money 总金额
	 * amount 发放数量*/
	private void RedRandom(int money,int amount) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("money", money);
		params.put("amount", amount);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_RED_PACKET_RANDOM_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "random_red_packet_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							JSONArray list = JsonUtils.getJSONArray(data, "list", new JSONArray());
							sendMsg(Global.AVIMCMD_Star_RedPapar, message,list.toString());
							et_red_packet_money_all.setText("");
							et_red_packet_number.setText("");
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/** 平均红包 
	 * money 单个金额
	 * amount 发放数量*/
	private void RedFixed(int money,int amount) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("money", money);
		params.put("amount", amount);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_RED_PACKET_FIXED_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "fixed_red_packet_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							JSONArray list = JsonUtils.getJSONArray(data, "list", new JSONArray());
							sendMsg(Global.AVIMCMD_Star_RedPapar, message,list.toString());
							et_red_packet_money_all.setText("");
							et_red_packet_number.setText("");
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	// 结束推流，注意做好清理工作
	public void stopRtmpPublish() {
		mLivePusher.stopCameraPreview(true); // 停止摄像头预览
		mLivePusher.stopPusher(); // 停止推流
		mLivePusher.setPushListener(null); // 解绑 listener
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mCaptureView.onPause();  // mCaptureView 是摄像头的图像渲染view
		mLivePusher.pausePusher(); // 通知 SDK 进入“后台推流模式”了
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mCaptureView.onResume();     // mCaptureView 是摄像头的图像渲染view
		mLivePusher.resumePusher();  // 通知 SDK 重回前台推流
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		LeaveRoom();
		super.onDestroy();
	}

	private void sendMsg(int userAction, String content,String ids) {
		// 构造一条消息
		TIMMessage msg = new TIMMessage();

		// 添加文本内容
		TIMTextElem elem = new TIMTextElem();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userAction", userAction);
			obj.put("nickName", Global.S_name);
			obj.put("userId", Global.U_id);
			obj.put("headPic", Global.headPic);
			obj.put("msg", content);
			obj.put("level", "1");
			
			if (!ids.equals("")) {
				JSONArray ary = new JSONArray(ids);
				String str = ary.toString().trim();
				obj.put("ids", str);
			}
			elem.setText(obj.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 将elem添加到消息
		if (msg.addElement(elem) != 0) {
			L.e(TAG, "addElement---", "addElement failed");
			return;
		}

		// 获取群聊会话

		TIMConversation conversation = TIMManager.getInstance()
				.getConversation(TIMConversationType.Group, // 会话类型：群组
						channel);
		// 发送消息
		conversation.sendMessage(msg, new TIMValueCallBack<TIMMessage>() {// 发送消息回调
					@Override
					public void onError(int code, String desc) {// 发送消息失败
						// 错误码code和错误描述desc，可用于定位请求失败原因
						// 错误码code含义请参见错误码表
						L.e(TAG, "send message failed. code: ---", code
								+ " errmsg: " + desc);
					}

					@Override
					public void onSuccess(TIMMessage msg) {// 发送消息成功
						L.e(TAG, "SendMsg ok.  ---", "");
						et_content.setText("");
						ll_btn.setVisibility(View.VISIBLE);
						ll_write.setVisibility(View.INVISIBLE);

						TIMTextElem elem = (TIMTextElem) msg.getElement(0);
						getIMMsg(elem.getText());
					}
				});
	}

	/** 获取礼物列表 */
	private void getGiftList() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("type", Global.U_type);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_GIFT_LIST_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "get_gift_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							JSONArray list = JsonUtils.getJSONArray(data, "list", new JSONArray());
							_list_gift.clear();
							_list_gift = JSONParser.getStarGiftList(list);
							if (_list_gift != null && _list_gift.size() > 0) {
								ll_gift.setVisibility(View.VISIBLE);
								ll_btn.setVisibility(View.INVISIBLE);
								ll_list.setVisibility(View.INVISIBLE);
								setGiftListData();
							} else {
								showToast("暂无礼物");
							}
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	private void setGiftListData() {
		positon = 1;
		tv_gift_name.setText(_list_gift.get(0).getG_name());
		tv_gift_sponsor.setText(_list_gift.get(0).getG_sponsor());
		tv_gift_num.setText(_list_gift.get(0).getG_amount());
		tv_gift_1.setTextColor(getResources().getColor(R.color.green));
		tv_gift_2.setTextColor(getResources().getColor(R.color.white));
		tv_gift_3.setTextColor(getResources().getColor(R.color.white));
		tv_gift_4.setTextColor(getResources().getColor(R.color.white));
		switch (_list_gift.size()) {
		case 0:
			tv_gift_1.setVisibility(View.INVISIBLE);
			tv_gift_2.setVisibility(View.INVISIBLE);
			tv_gift_3.setVisibility(View.INVISIBLE);
			tv_gift_4.setVisibility(View.INVISIBLE);
			break;
		case 1:
			tv_gift_1.setText(_list_gift.get(0).getG_name());
			tv_gift_1.setVisibility(View.VISIBLE);
			tv_gift_2.setVisibility(View.INVISIBLE);
			tv_gift_3.setVisibility(View.INVISIBLE);
			tv_gift_4.setVisibility(View.INVISIBLE);
			break;
		case 2:
			tv_gift_1.setText(_list_gift.get(0).getG_name());
			tv_gift_2.setText(_list_gift.get(1).getG_name());
			tv_gift_1.setVisibility(View.VISIBLE);
			tv_gift_2.setVisibility(View.VISIBLE);
			tv_gift_3.setVisibility(View.INVISIBLE);
			tv_gift_4.setVisibility(View.INVISIBLE);
			break;
		case 3:
			tv_gift_1.setText(_list_gift.get(0).getG_name());
			tv_gift_2.setText(_list_gift.get(1).getG_name());
			tv_gift_3.setText(_list_gift.get(2).getG_name());
			tv_gift_1.setVisibility(View.VISIBLE);
			tv_gift_2.setVisibility(View.VISIBLE);
			tv_gift_3.setVisibility(View.VISIBLE);
			tv_gift_4.setVisibility(View.INVISIBLE);
			break;
		case 4:
			tv_gift_1.setText(_list_gift.get(0).getG_name());
			tv_gift_2.setText(_list_gift.get(1).getG_name());
			tv_gift_3.setText(_list_gift.get(2).getG_name());
			tv_gift_4.setText(_list_gift.get(3).getG_name());
			tv_gift_1.setVisibility(View.VISIBLE);
			tv_gift_2.setVisibility(View.VISIBLE);
			tv_gift_3.setVisibility(View.VISIBLE);
			tv_gift_4.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
	}

	/** 发送礼物 */
	private void sendGift(String gid, String num) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("gid", gid);
		params.put("amount", num);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_GIFT_STAR_SEND_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "send_gift_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							JSONArray list = JsonUtils.getJSONArray(data, "list", new JSONArray());
							sendMsg(Global.AVIMCMD_Star_Present, message,list.toString());
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.ib_back:
			LeaveRoom();
			break;
		case R.id.btn_write:
			ll_btn.setVisibility(View.INVISIBLE);
			ll_write.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_red_packet:
			getAccountMoney();
			break;
		case R.id.btn_overturn:
			mLivePusher.switchCamera();
			break;
		case R.id.btn_share:
			DialogShareView dsv = new DialogShareView(context);
			String urlString  = Urls.SHARE_URL+"Share/Lives?channel="+channel;
			dsv.initLiveDialog(urlString,shareTitle,shareContent);
			break;
		case R.id.btn_beauty:
			if (isBeautify) {
				mLivePusher.setBeautyFilter(0, 0);
			}else{
				mLivePusher.setBeautyFilter(5, 3);
			}
			isBeautify=!isBeautify;
			break;
		case R.id.radio_average:
			et_red_packet_money_all.setHint("输入每个红包金额");
			break;
		case R.id.radio_random:
			et_red_packet_money_all.setHint("输入红包总金额");
			break;
		case R.id.ib_close_red_pakcet:
			ll_btn.setVisibility(View.VISIBLE);
			ll_list.setVisibility(View.VISIBLE);
			ll_red_packet.setVisibility(View.INVISIBLE);
			break;
		case R.id.btn_send_red_packet:
			ll_btn.setVisibility(View.VISIBLE);
			ll_list.setVisibility(View.VISIBLE);
			ll_red_packet.setVisibility(View.INVISIBLE);
			
			String str_money_all = et_red_packet_money_all.getText().toString().trim();
			String str_money_number = et_red_packet_number.getText().toString().trim();
			
			//平均
			if (radio_average.isChecked()) {
				if (StringUtils.isBlank(str_money_all)) {
					showToast("请输入每个红包金额！");
					return;
				}
				if (StringUtils.isBlank(str_money_number)) {
					showToast("请输入人数！");
					return;
				}
				int money = Integer.valueOf(str_money_all);
				int amount = Integer.valueOf(str_money_number);
				RedFixed(money, amount);
			}
			//随机
			if (radio_random.isChecked()) {
				if (StringUtils.isBlank(str_money_all)) {
					showToast("请输入红包总金额！");
					return;
				}
				if (StringUtils.isBlank(str_money_number)) {
					showToast("请输入人数！");
					return;
				}
				int money = Integer.valueOf(str_money_all);
				int amount = Integer.valueOf(str_money_number);
				RedRandom(money, amount);
			}
			break;
		case R.id.btn_send_msg:
			String content = et_content.getText().toString().trim();
			if (TextUtils.isEmpty(content)) {
				showToast("发送内容不能为空！");
				break;
			}
			sendMsg(Global.AVIMCMD_Custom_Text, content,"");
			break;
		case R.id.btn_gift:
			getGiftList();
			break;
		case R.id.btn_send_msg_gift:
			ll_gift.setVisibility(View.INVISIBLE);
			ll_btn.setVisibility(View.VISIBLE);
			ll_list.setVisibility(View.VISIBLE);
			if (positon == 1) {
				sendGift(_list_gift.get(0).getG_id(), tv_gift_num_choice.getText().toString());
			}
			break;
		case R.id.btn_jia:
			{String str_num = tv_gift_num_choice.getText().toString();
			int int_num = Integer.valueOf(str_num);
			int_num++;
			String str_amount= _list_gift.get(positon-1).getG_amount();
			int int_amount = Integer.valueOf(str_amount);
			if (int_num>int_amount) {
				showToast("总数不能超过库存");
				int_num--;
			}
			tv_gift_num_choice.setText(String.valueOf(int_num));}
			break;
		case R.id.btn_jian:
			{String str_num = tv_gift_num_choice.getText().toString();
			int int_num = Integer.valueOf(str_num);
			int_num--;
			
			if (int_num<=0) {
				showToast("总数不能小于1");
				int_num++;
			}
			tv_gift_num_choice.setText(String.valueOf(int_num));}
			break;
		case R.id.tv_clear:
			tv_gift_num_choice.setText("1");
			break;
		case R.id.tv_gift_1:
			positon = 1;
			tv_gift_name.setText(_list_gift.get(0).getG_name());
			tv_gift_sponsor.setText(_list_gift.get(0).getG_sponsor());
			tv_gift_num.setText(_list_gift.get(0).getG_amount());
			tv_gift_1.setTextColor(getResources().getColor(R.color.green));
			tv_gift_2.setTextColor(getResources().getColor(R.color.white));
			tv_gift_3.setTextColor(getResources().getColor(R.color.white));
			tv_gift_4.setTextColor(getResources().getColor(R.color.white));
			break;
		case R.id.tv_gift_2:
			positon = 1;
			tv_gift_name.setText(_list_gift.get(1).getG_name());
			tv_gift_sponsor.setText(_list_gift.get(1).getG_sponsor());
			tv_gift_num.setText(_list_gift.get(1).getG_amount());
			tv_gift_1.setTextColor(getResources().getColor(R.color.white));
			tv_gift_2.setTextColor(getResources().getColor(R.color.green));
			tv_gift_3.setTextColor(getResources().getColor(R.color.white));
			tv_gift_4.setTextColor(getResources().getColor(R.color.white));
			break;
		case R.id.tv_gift_3:
			positon = 1;
			tv_gift_name.setText(_list_gift.get(2).getG_name());
			tv_gift_sponsor.setText(_list_gift.get(2).getG_sponsor());
			tv_gift_num.setText(_list_gift.get(2).getG_amount());
			tv_gift_1.setTextColor(getResources().getColor(R.color.white));
			tv_gift_2.setTextColor(getResources().getColor(R.color.white));
			tv_gift_3.setTextColor(getResources().getColor(R.color.green));
			tv_gift_4.setTextColor(getResources().getColor(R.color.white));
			break;
		case R.id.tv_gift_4:
			positon = 1;
			tv_gift_name.setText(_list_gift.get(3).getG_name());
			tv_gift_sponsor.setText(_list_gift.get(3).getG_sponsor());
			tv_gift_num.setText(_list_gift.get(3).getG_amount());
			tv_gift_1.setTextColor(getResources().getColor(R.color.white));
			tv_gift_2.setTextColor(getResources().getColor(R.color.white));
			tv_gift_3.setTextColor(getResources().getColor(R.color.white));
			tv_gift_4.setTextColor(getResources().getColor(R.color.green));
			break;
		case R.id.iv_adv1:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(0).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		case R.id.iv_adv2:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(1).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		case R.id.iv_adv3:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(2).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		case R.id.iv_adv4:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(3).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ll_write.setVisibility(View.INVISIBLE);
			ll_gift.setVisibility(View.INVISIBLE);
			ll_btn.setVisibility(View.VISIBLE);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
